/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.runtime.component
{
	import com.edi.proxy.component.*;
	import com.edi.runtime.Event.*;
	import com.edi.utils.HashMap;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ICollectionView;
	import mx.containers.Canvas;
	import mx.controls.Button;
	import mx.controls.TextInput;
	import mx.core.Application;
	import mx.events.FlexEvent;
	/**
	 * 基础资料显示控件,包括文本框和按钮,调用弹出窗口EDIBasicDataWindow显示基础资料 
	 * <p>在MXML中用法：</p>
	 * <p>例：<EDIBasicData treeItemID="Services.serviceGetServerUnits" treeLabelField="caption" treeIDField="id" treepidField="parentid"</p> 
	 * <p>treeRootValue="0" itemID="Services.serviceGetUnitUsers" itemParentID="parentid" displayField="caption"  primaryKey="false"    saveField="id" id="receiveName"   visible="true"  notNull="true" fieldLength="50" fieldType="string"  table="MailItem" field="receivename"   ></EDIBasicData></p>
	 * <p>treeItemID：弹出窗口中左边树形结构的数据来源,可以是基础资料ID和服务名</p>
	 * <p>treeLabelField：树形结构节点文本的字段名</p>
	 * <p>treeIDField：树形结构节点的ID字段名</p>
	 * <p>treepidField：树形数据源中节点指向父节点的字段名</p>
	 * <p>treeRootValue：树的根节点ID值</p>
	 * <p>itemID：表格数据来源,可以是基础资料ID和服务名</p>
	 * <p>itemParentID：表格数据源中与树形数据源id对应的字段名</p>
	 * <p>displayField：选择完毕后需要在EDIBasicData文本框中显示的字段名</p>
	 * 
	 * 
	 */	
	public class EDIBasicData extends Canvas implements IEDIComponent
	{ 
		private var _dataField:String;
		private var _remoteFiled:String;
		private var _field:String;
		private var _fieldType:String;
		private var _dataSourceName:String="";
		private var _xlist:ICollectionView;
		private var _table:String;
		private var _primaryKey:String;
		
		private var _remoteService:String;
		
		private var FBtn:Button;
		private var FTextInput:TextInput;
		private var FEDIBasicDataWindow:EDIBasicDataWindow;
		
		private var _ediApp:EDIApplication;
		private var visibleFieldObj:Object=new Object();
		private var proxy:HttpProxy;
		/**
		 * 应用名称
		 */		
		public var appName:String;
		/**
		 * 基础资料名称
		 */		
		public var itemID:String;
		/**
		 * 树状基础资料表名
		 */		
		public var treeItemID:String;	
		/**
		 * 树状根节点上级id
		 */		
		public var treeRootValue:String;	
		/**
		 * 树形显示节点
		 */		
		public var treeLabelField:String;
		/**
		 * 树形id字段
		 */		
		public var treeIDField:String;
		/**
		 * 树形上级字段
		 */		
		public var treepidField:String;
		/**
		 * 基础资料和树形资料关联字段
		 */		
		public var itemParentID:String;
		/**
		 * 如果基础资料来源于本系统，sourceTable是来源表的名称
		 */		
		public var sourceTable:String;
		/**
		 * 弹出窗口宽度
		 */		
		public var winWidth:int=0;
		/**
		 * 弹出窗口高度
		 */		
		public var winHeight:int=0;
		/**
		 * 基础资料弹出窗口点“确定”后回调函数
		 */		
		public var callback:Function;
		/**
		 * 已选择的基础资料清单
		 */		
		public var returnArr:ArrayCollection=new ArrayCollection();
		
		/**
		 * 保存在数据库中不为空
		 */		
		public var notNull:Boolean;
		/**
		 * 保存在数据库字段长度
		 */		
		public var fieldLength:int;
		/**
		 * 需要保存在数据库 的字段名称
		 */		
		public var saveField:String="";
		/**
		 * 在基础资料文本框中显示的字段名
		 */		
		public var displayField:String="";
		
		/**
		 * 保存在数据库中的值
		 */		
		[Bindable]
		public var saveValue:String;
		
		/**
		 * 与服务器通信所有变量
		 */		
		public var ediSessionId:String;
		/**
		 * 与服务器通信所有变量
		 */		
		public var ds:EDIDataSource;
		/**
		 * 与服务器通信所有变量
		 */		
		public var url:String;
		/**
		 * 是否为多选 --build by hw
		 */		
		public var multiSelect:Boolean;
		 /**
		 *数据源名称 --build by hw
		 */
		 public var datasouName:String="tb_tree";
		 /**
		 * 是否为逻辑删除(逻辑删除需要存在字段isdel来标示,0为未删除,1为删除.数据库中为bit类型,默认为物理删除,即直接删除数据库中的数据.)
		 */
		 public var logicDelete:Boolean = false;
		 
		 /**
		 * 服务中需要传递的参数.默认长度为空.
		 */
		 public var paramMap:HashMap = new HashMap();
		/**
		 * 构造函数 传入参数赋值，并构造EDIBasicData的可视化组件
		 * @param appName 应用名
		 * @param itemID 表格数据源对应基础资料名
		 * @param treeItemID 树形数据源对应基础资料名
		 * @param treeRootValue 树形根节点值
		 * @param treeLabelField 树形节点显示字段名
		 * @param treeIDField 树形节点ID字段名
		 * @param treepidField 树形节点指向父节点字段名
		 * @param itemParentID 表格数据源中与树形数据源id对应的字段名
		 * 
		 */		
		public function EDIBasicData(appName:String="",itemID:String="",treeItemID:String="",treeRootValue:String="0",treeLabelField:String="",treeIDField:String="",treepidField:String="",itemParentID:String="")
		{
			super();
			this.width=200;
			this.height=25;
			//this.multiselect=multiselect;
			this.appName=appName;
			this.itemID=itemID;
			this.treeItemID=treeItemID;
			this.treeRootValue=treeRootValue;
			this.treeLabelField=treeLabelField;
			this.treeIDField=treeIDField;
			this.treepidField=treepidField;
			this.itemParentID=itemParentID;
			
			//EDIApplication.outputDebug("inner.isMultiSelect.this.multiselect:  "+this.multiselect);
			//EDIApplication.outputDebug("inner.multiSelect.multiselect:   "+multiselect);
			this.horizontalScrollPolicy="off";
			this.verticalScrollPolicy="off";
			
			FTextInput=new TextInput();
			FTextInput.setStyle("borderStyle","solid");
			FTextInput.setStyle("borderColor:","#BBBBBF");
			FTextInput.setStyle("themeColor","#E9EBF8");
			FTextInput.setStyle("fontSize","12");
			FTextInput.editable=false;
			
			FBtn=new Button();
			FBtn.setStyle("borderColor:","#000000");
			FBtn.addEventListener(MouseEvent.CLICK,btnClickHandler);
			this.addEventListener(FlexEvent.CREATION_COMPLETE,createHandler);
			
			this.addChild(FTextInput);
			this.addChild(FBtn);
			//FEDIBasicDataWindow=new EDIBasicDataWindow(appName,itemID,treeItemID,treeRootValue,treeLabelField,treeIDField,treepidField,itemParentID);
		}
		/**
		 * FlexEvent.CREATION_COMPLETE后触发，初始化proxy
		 * @param event
		 * 
		 */		
		private function createHandler(event:Event):void
		{
			_ediApp=EDIApplication(this.parentApplication);
			this.appName=EDIApplication.appName;

			if(sourceTable)
			{
				sourceTable=itemID;
				
			}
		}
		
		/****
		 * 将basicdata对象设置为不可编辑
		 */
		public function set enable(value:Boolean):void{
			this.FBtn.enabled = value;
			this.FTextInput.editable = value;
		}
		/**
		 * 重新设置内部可视化组件的位置和大小 
		 * @param w
		 * @param h
		 * 
		 */		
		override public function setActualSize(w:Number, h:Number):void
		{	
			super.setActualSize(w,h);
			FTextInput.x=0;
			FTextInput.y=0;
			FTextInput.width=w;
			FTextInput.height=h;
			
			FBtn.x=w-20;
			FBtn.width=20;
			FBtn.height=h;
		}
		
		public function setReturnField(displayFiled:String):void{
			this.displayField = displayFiled;
		}
		
		/**
		 * 按钮点击事件处理，显示基础资料窗口 
		 * @param event
		 * 
		 */		
		public function btnClickHandler(event:MouseEvent):void
		{
			showBasicWindow();
		}
		/**
		 *	弹出基础资料窗口方法，设置环境变量、大小等
		 * 
		 */		
		public function showBasicWindow():void
		{
			//EDIApplication.outputDebug("isMultiSelect:  "+this.multiselect);
			if(!FEDIBasicDataWindow)
			{
				FEDIBasicDataWindow=new EDIBasicDataWindow(itemID,treeItemID,treeRootValue,treeLabelField,treeIDField,treepidField,itemParentID,multiSelect,callback,datasouName,logicDelete,paramMap);
				FEDIBasicDataWindow.displayField=this.displayField;
				FEDIBasicDataWindow.saveField=this.saveField;
				winHeight=screen.height;
				winWidth=screen.width;
				
				FEDIBasicDataWindow.setReturnField(displayField);
				
				FEDIBasicDataWindow.parentApp=Application(_ediApp);
				FEDIBasicDataWindow.ediBasicData=this;
				
				for(var str:String in visibleFieldObj)
				{
					FEDIBasicDataWindow.setVisibleField(str);
				}
				FEDIBasicDataWindow.height=winHeight;
				FEDIBasicDataWindow.width=winWidth;
			}
			FEDIBasicDataWindow.returnArr=this.returnArr;
//			EDIAlert.show("returnArr:"+returnArr.length.toString());

			FEDIBasicDataWindow.returnTxt=this.FTextInput;
			FEDIBasicDataWindow.showModel();
		}
		/**
		 * 指定表格数据源中那些列可以显示，可以指定多个字段
		 * @param col
		 * 
		 */		
		public function setVisibleField(col:String):void
		{
			//调用该函数指定显示的列
			visibleFieldObj[col]=col;
		}
		/****
		 * 是否多选的get,set方法
		 * */


		/**
		 * 保存表名，IEDIComponent接口需要的属性
		 * @param value
		 * 
		 */		
		public function set table(value:String):void
		{
			_table=value;
			EDIEventProxy.listenerDataRolling(value,this);
		}
		public function get table():String
		{return _table;}
		/**
		 * 是否主键，IEDIComponent接口需要的属性 
		 * @param value
		 * 
		 */
		public function set primaryKey(value:String):void
		{_primaryKey=value;}
		public function get primaryKey():String
		{return _primaryKey;}
		
		/**
		 * 保存字段名，IEDIComponent接口需要的属性 
		 * @param value
		 * 
		 */		
		public function set field(value:String):void
		{_field=value;}
		public function get field():String
		{return _field}
		/**
		 * IEDIComponent接口需要的属性 
		 * @param value
		 * 
		 */		
		public function set fieldType(value:String):void
		{_fieldType=value;}
		public function get fieldType():String
		{return _fieldType}
		
		/**
		 * 如果基础资料是远程服务
		 * @param value
		 * 
		 */		
		public function set remoteService(value:String):void
		{
			//_remoteService=value;
			itemID=value;
		}
		public function get remoteService():String
		{
			return itemID;//_remoteService
		}

		/**
		 * 直接给EDIBasicData的文本框进行赋值
		 * @param value
		 * 
		 */		
		public function set text(value:String):void
		{
			if(value==null)
			{	
				value="";
			}
			FTextInput.text=value;
		}
		public function get text():String
		{
			return FTextInput.text;
		}
		/**
		 * 设置ediValue值，IEDIComponent接口需要的属性 
		 * @return 
		 * 
		 */		
		public function get ediValue():String
		{
			return this.saveValue;
		}
	
		public function set ediValue(value:String):void
		{
			var eql:String;
			this.saveValue=value;
			//Alert.show("set ediValue:"+sourceTable+"."+value);
			if(itemID.indexOf("Services")==0)
			{
				var arr:Array=new Array();
				var para1:Object=new Object();
				para1["name"]="id";
				para1["value"]=value;
				arr.push(para1);
				
				ServerProxy.getWebInfo("detail",this.itemID+"ById","",arr,getEqlDataHandeler);			
			}
			else
			{
				eql="select "+displayField+" as displayfield from "+itemID+" where "+saveField+"='"+saveValue+"'";
				//Alert.show(eql);
				var desPara:EPOParam=new EPOParam();
				proxy=new HttpProxy(this.appName,true,this.ds);
				proxy.url=EDIApplication.path+EDIApplication.appName+".app";
				//"app1"需要被this.appName代替
				desPara.EQL =eql;
				//TODO下面这句需要重写
				desPara.dsName = itemID;
				proxy.addPoParam(desPara);
				proxy.send();
				proxy.resultCallback=getEqlDataHandeler;
			}
			
		}
		/**
		 * 数据自动分发方法，IEDIComponent接口需要的方法
		 * @param event
		 * 
		 */		
		public function dataRollingHandler(event:EDIDataEvent):void
		{
			ediValue=event.value[field];
		}
		/**
		 * 从服务器端获取数据后对文本框自动赋值
		 * @param event
		 * 
		 */		
		private function getEqlDataHandeler(event:HttpProxyResult):void
		{
			while(event.poNext())
			{
				if(itemID.indexOf("Services")==0)
				{
					text=event.currentPoResult.object.String;
				}
				else
				{
					if(XML(event.currentPoResult.dataSource.table).elements().length()>0)
						text=event.currentPoResult.dataSource.table.row[0].displayfield;
				}
				var obj:Object=new Object();
				obj["id"]=this.ediValue;
				obj["caption"]=text;
				this.returnArr.addItem(obj);
			}
		}
		/**
		 * 文本框是否可编辑
		 * @param value
		 * 
		 */

		public function set editable(value:Boolean):void
		{
			this.FTextInput.editable=value;
		}
		public function get editable():Boolean
		{
			return this.FTextInput.editable;
		}
		public function setFEDIBasicDataWindowISNULL():void
		{
			FEDIBasicDataWindow=null;
		}
	}
}